<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.keyYouth_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button type="text"
                   icon="el-icon-setting"
                   size="small"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click.stop="handleDataSub(row)">帮 扶
        </el-button>
      </template>
    </avue-crud>

    <el-dialog :title="帮扶情况" append-to-body :visible.sync="subVisible" :direction="direction"
                size="1300px">
      <basic-container>
        <avue-crud :option="optionSub"
                   :data="dataSub"
                   :page="pageSub"
                   v-model="formSub"
                   :table-loading="loadingSub"
                   ref="crudSub"
                   @row-del="rowDelSub"
                   @row-update="rowUpdateSub"
                   @row-save="rowSaveSub"
                   :before-open="beforeOpenSub"
                   @search-change="searchChangeSub"
                   @search-reset="searchResetSub"
                   @selection-change="selectionChangeSub"
                   @current-change="currentChangeSub"
                   @refresh-change="refreshChangeSub"
                   @size-change="sizeChangeSub"
                   @on-load="onLoadSub">
          <template slot="menuLeft">
            <el-button type="danger"
                       size="small"
                       icon="el-icon-delete"
                       plain
                       @click="handleDeleteSub">删 除
            </el-button>
          </template>
        </avue-crud>
      </basic-container>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,getDetailByCard} from "@/api/ninebasic/keyPersonnel/keyYouth";
  import {getList as getListSub, getDetail as getDetailSub, add as addSub, update as updateSub, remove as removeSub} from "@/api/ninebasic/keyPersonnel/personnelHelp";
  import {mapGetters} from "vuex";
  import {validatenull,isvalidatemobile,cardid} from "@/util/validate";
  import {getPopulation} from "@/api/ninebasic/realpop/allPopulation";
  export default {
    data() {
      //手机号校验非空
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };  
      //校验身份正号码
      const validateCardid = (rule, value, callback) => {
        if(cardid(value)[0]){
          callback(new Error(cardid(value)[1]))
        }else{
          callback();
        }
      };
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          dialogWidth: 1250,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          excelBtn: false,
          dialogClickModal: false,
          column: [
            {
              label: "主键",
              prop: "id",
              type: "input",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: true,
            },
             {
              label: "所属网格",
              prop: "gridId",
              type: "tree",
              span: 24,
              parent: true,
              display: true,
              dicMethod: "get",
              dicUrl: "/api/smart-system/dept/treeByPid",
              props: {
                label: "title",
                vlaue:  "key"
              },
              checkStrictly: true,
              search: true,
              rules: [{
                required: true,
                message: "请输入所属网格",
                trigger: "click"
              }],
            },
            {
              label: "身份证号码",
              prop: "idCardNo",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                //validator: validateCardid,
                message: "请输入身份号码",
                trigger: "blur"
              }],
               blur: ({value}) => {
                 if(!validatenull(this.form.gridId)){
                    getDetailByCard(value,this.form.gridId).then(res => {
                      if(validatenull(res.data.data)) {
                        getPopulation(this.form.gridId,value).then(res => {
                          console.log(res.data);
                          if(!validatenull(res.data.data)) {
                                this.form.id = res.data.data.id;
                                this.form.name = res.data.data.name;
                                this.form.sex = res.data.data.sex;
                                this.form.birthday = res.data.data.birthday;
                                this.form.mobile = res.data.data.mobile;
                                this.form.liveAddrDetail = res.data.data.liveAddrDetail;
                                this.form.serviceSpace = res.data.data.serviceSpace; 
                          } else{
                            this.$message.error("身份证格式不正确或实有人口中不存在该人员，请先进行实有人员维护");
                          }
                        })
                      }else{
                           this.$message.error("该身份证号已存在");
                      }  
                    })
                 }else{
                   this.$message.error("请先选择网格");
                 }
               }
            },
            {
              label: "姓名",
              prop: "name",
              type: "input",
              readonly: true,
              disabled:true,
              search: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }],
            },
            {
              label: "性别 ",
              prop: "sex",
              type: "select",
              readonly: true,
              disabled:true,
              dicUrl: "/api/smart-system/dict/dictionary?code=sex",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入性别 ",
                trigger: "blur"
              }],
            },
            {
              label: "出生日期",
              prop: "birthday",
              type: "date",
              readonly: true,
              disabled:true,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              span: 8,
              rules: [{
                required: true,
                message: "请输入出生日期",
                trigger: "blur"
              }],
            },
            {
              label: "服务处所",
              prop: "serviceSpace",
              type: "input",
              readonly: true,
              disabled:true,
              span: 8,
              hide: true,
            },
            {
              label: "联系方式",
              prop: "mobile",
              type: "input",
              readonly: true,
              disabled:true,
              search: true,
              span: 8,
              rules: [{
                required: true,
                validator: validatePhone,
                //message: "请输入联系方式",
                trigger: "blur"
              }],
            },
            {
              label: "现住详址",
              prop: "liveAddrDetail",
              type: "input",
              hide: true,
              readonly: true,
              disabled:true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入现住详址",
                trigger: "blur"
              }],
            },
            {
              label: "人员类型",
              prop: "personnelType",
              type: "select",
              overHidden:true,
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=personnel_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              search: true,
              rules: [{
                required: true,
                message: "请输入人员类型",
                trigger: "blur"
              }],
            },
            {
              label: "家庭情况",
              prop: "familySituation",
              type: "select",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=family_situation",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入家庭情况",
                trigger: "blur"
              }],
            },
            {
              label: "监护人身份证",
              prop: "guardianIdCard",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                validator: validateCardid,
                //message: "请输入监护人身份证",
                trigger: "blur"
              }],
            },
            {
              label: "监护人姓名",
              prop: "guardianName",
              type: "input",
              search: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入监护人姓名",
                trigger: "blur"
              }],
            },
            {
              label: "与监护人关系",
              prop: "relation",
              type: "select",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=household_relation",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入与监护人关系",
                trigger: "blur"
              }],
            },
            {
              label: "监护人联系方式",
              prop: "guardianContact",
              type: "input",
              search: true,
              span: 8,
              rules: [{
                required: true,
                validator: validatePhone,
                //message: "请输入监护人联系方式",
                trigger: "blur"
              }],
            },
            {
              label: "监护人居住详址",
              prop: "guardianAddrDetail",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入监护人居住详址",
                trigger: "blur"
              }],
            },
            {
              label: "是否违法犯罪",
              prop: "isCrime",
              type: "radio",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=yes_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入是否违法犯罪",
                trigger: "blur"
              }],
            },
            {
              label: "违法犯罪情况",
              prop: "crimeSituation",
              type: "input",
              span: 8,
              hide: true,
            },
            {
              label: "帮扶人姓名",
              prop: "helperName",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入帮扶人姓名",
                trigger: "blur"
              }],
            },
            {
              label: "帮扶人联系方式",
              prop: "helperContact",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                validator: validatePhone,
                //message: "请输入帮扶人联系方式",
                trigger: "blur"
              }],
            },
            {
              label: "帮扶方式",
              prop: "helpMode",
              type: "select",
              span: 8,
              dicUrl: "/api/smart-system/dict/dictionary?code=helping_means",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入帮扶方式",
                trigger: "blur"
              }],
            },
            {
              label: "帮扶情况",
              prop: "helpSituation",
              type: "textarea",
              span: 24,
              hide: true,
            },
          ]
        },
        data: [],
        subVisible: false,
        direction: 'rtl',
        keyYouthId: 0,
        keyYouthName: "重点青少年",
        formSub: {},
        querySub: {},
        loadingSub: true,
        dataSub: [],
        selectionListSub: [],
        pageSub: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        optionSub:{
          height: 'auto',
          calcHeight: 30,
        
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          excelBtn: false,
          dialogClickModal: false,
            column: [
              {
                label: "主键",
                prop: "id",
                type: "input",
                addDisplay: false,
                editDisplay: false,
                viewDisplay: false,
                hide: true,
              },
              {
                label: "重点人员id",
                prop: "personnelId",
                type: "input",
                addDisplay: false,
                editDisplay: false,
                viewDisplay: false,
                hide: true,
              },
              {
                label: "帮扶时间",
                prop: "helpTime",
                type: "date",
                format: "yyyy-MM-dd",
                valueFormat: "yyyy-MM-dd",
                rules: [{
                  required: true,
                  message: "请输入帮扶时间",
                  trigger: "blur"
                }],
              },
              {
                label: "帮扶人姓名",
                prop: "helperName",
                type: "input",
                search: false,
                rules: [{
                  required: true,
                  message: "请输入帮扶人姓名",
                  trigger: "blur"
                }],
              },
              {
                label: "帮扶人单位",
                prop: "helperCompany",
                type: "input",
                rules: [{
                  required: true,
                  message: "请输入帮扶人单位",
                  trigger: "blur"
                }],
              },
              {
                label: "帮扶人联系方式",
                prop: "helperContact",
                type: "input",
                rules: [{
                  required: true,
                  message: "请输入帮扶人联系方式",
                  trigger: "blur"
                }],
              },
              {
                label: "帮扶原因",
                prop: "helperReason",
                type: "input",
                span: 24,
                hide: true,
                rules: [{
                  required: true,
                  message: "请输入帮扶原因",
                  trigger: "blur"
                }],
              },
              {
                label: "帮扶内容",
                prop: "helperContent",
                type: "textarea",
                span: 24,
                hide: true,
                rules: [{
                  required: true,
                  message: "请输入帮扶内容",
                  trigger: "blur"
                }],
              },
            ]
        },
      };
    },
    watch: {
    
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.keyYouth_add, false),
          viewBtn: this.vaildData(this.permission.keyYouth_view, false),
          delBtn: this.vaildData(this.permission.keyYouth_delete, false),
          editBtn: this.vaildData(this.permission.keyYouth_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      subIds() {
        let ids = [];
        this.selectionListSub.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        //新增和修改页面，控制网格树加载职能选择末级，查询页面可以选择父级
        if (["edit", "add"].includes(type)) {
            const gridId = this.findObject(this.option.column,"gridId");
            gridId.parent = false;
           
        }
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      // 子表模块
      handleDataSub(row) {
        this.subVisible = true;
        this.personnelId = row.id;
        this.onLoadSub(this.pageSub)
      },
      handleSubClose(hide) {
        hide();
      },
      rowSaveSub(row, loading, done) {
        row = {
          ...row,
          personnelId: this.personnelId,
        };
        addSub(row).then(() => {
          loading();
          this.onLoadSub(this.pageSub);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          done();
          window.console.log(error);
        });
      },
      rowUpdateSub(row, index, loading, done) {
        row = {
          ...row,
          keyYouthId: this.keyYouthId,
        };
        updateSub(row).then(() => {
          loading();
          this.onLoadSub(this.pageSub);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          done();
          window.console.log(error);
        });
      },
      rowDelSub(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeSub(row.id);
          })
          .then(() => {
            this.onLoadSub(this.pageSub);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDeleteSub() {
        if (this.selectionListSub.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeSub(this.subIds);
          })
          .then(() => {
            this.onLoadSub(this.pageSub);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crudSub.toggleSelection();
          });
      },
      beforeOpenSub(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetailSub(this.formSub.id).then(res => {
            this.formSub = res.data.data;
          });
        }
        done();
      },
      searchResetSub() {
        this.querySub = {};
        this.onLoadSub(this.pageSub);
      },
      searchChangeSub(params) {
        this.querySub = params;
        this.onLoadSub(this.pageSub, params);
      },
      selectionChangeSub(list) {
        this.selectionListSub = list;
      },
      currentChangeSub(currentPage) {
        this.pageSub.currentPage = currentPage;
      },
      sizeChangeSub(pageSize) {
        this.pageSub.pageSize = pageSize;
      },
      refreshChangeSub() {
        this.onLoad(this.page, this.query);
      },
      onLoadSub(page, params = {}) {
        this.loadingSub = true;
        const values = {
          ...params,
          personnelId: this.personnelId,
        }
        getListSub(page.currentPage, page.pageSize, Object.assign(values, this.querySub)).then(res => {
          const data = res.data.data;
          this.pageSub.total = data.total;
          this.dataSub = data.records;
          this.selectionListSub = [];
          this.loadingSub = false;
        });
      },
    }
  };
</script>

<style>
.el-form-item__content{
   margin-left: 130px ! important;
}
.el-form-item__label {
  width: 130px ! important;
}
</style>
